/*
 Routine to precharge everything and pay attention to parameters
*/

#include <p30F4011.h>
#include "settings.h"
#include "AC-Controller.h"
#include "globals.h"
#include "eeprom.h"
#include "precharge.h"

	/*Now that the hardware is initialized we've got to take care to precharge. After precharge is done
	//go ahead and throw in the main contactor then drop out the precharge circuit
	//If you are using a LEV200 with sense wires then you get a cookie. Otherwise you'll likely not be
	//able to do the detection of main contactor state.
	//State flow chart:
	//1. Check to see if main contactor shows to be active. If so abort everything and keep PWM at zero!
	//2. Otherwise enable the precharge contactor
	//3. Monitor the voltage to watch for a tapering off of voltage. If that doesn't happen within a set time
		 then abort everything and keep PWM at zero. This requires being able to watch the HV. If you can't
		 do that then just precharge for a set time and call it good
	//4. Enable the main contactor, wait a tiny bit (like 250ms), then drop the precharge contactor
	//5. If all that went well then set Running to true and Precharged to true
	//
	//For reference, C13 is the main contactor and C14 is precharge. Use D2 for the sense if you have
	//sense leads on your main contactor. The board (when I actually put it together) should power one wire of
	//the sense leads through like a 1-5k resistor and see if voltage shows up on the other pin (at D2). This
	//can just be a digital input.
	*/



int precharge(void) {
    int precharge_delay;
    int precharge_ticks;
    unsigned long start_tick;
    int vgrad_1=0, vgrad_2=0;

    precharge_delay = ee_get_precharge_time();
    precharge_ticks = precharge_delay << 4; //that's x16 for those of you playing our home game

    if (use_hardware & EE_USE_MAIN_CONTACTOR_SENSE) {
        //sense whether mc is shut and throw a fit if it is
    }
    //turn on precharge
    SET_HIGH(PRECHARGE_RELAY);
    //now, sit in a loop waiting for enough ticks to go by for failing the test
    //if we abort the loop early then it's apparent the voltage test went OK
    start_tick = sys_ticks;
 /*   while ((sys_ticks - start_tick) < precharge_ticks) {
        delay_ms(100); //delay a 1/10th of a second
        //check voltage gradient. If less than 2 gradients happened then we're really well charged
        vgrad_2 = hv_raw_input;
        if (vgrad_2 < 5) return PRECHARGE_NO_HV; //after 100ms we should have more voltage than that. So, obviously something is wacked
        if ((vgrad_2 - vgrad_1) < 4) return PRECHARGE_OK;
    } */

    delay_ms(precharge_delay); //wait the proper amount of time
    return PRECHARGE_OK;

    //return PRECHARGE_TOO_LONG;
}
